package cn.jcet.module.sys.controller;

import cn.jcet.common.utils.ActiverUser;
import cn.jcet.common.utils.ResultObj;
import cn.jcet.common.utils.WebUtils;
import cn.jcet.module.api.LoginControllerApi;
import cn.jcet.module.sys.domain.LogInfo;
import cn.jcet.module.sys.service.ILogInfoService;
import cn.jcet.module.sys.vo.UserVo;
import com.google.code.kaptcha.Producer;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;

@Controller
@RequestMapping("/login")
public class LoginController implements LoginControllerApi {

    @Autowired
    private ILogInfoService ILogInfoService;

    @PostMapping(value = "/login")
    @ResponseBody
    public ResultObj login(UserVo UserVo){
        try {
            //获取域中的验证码
            String code = WebUtils.getSession().getAttribute("code").toString();
            //输入的验证码和域中验证码对比是否一致
            if(UserVo.getCaptcha().equals(code)){
                Subject subject = SecurityUtils.getSubject();
                //传入用户名和密码
                AuthenticationToken token=new UsernamePasswordToken(UserVo.getLoginname(), UserVo.getPwd());
                //登录
                subject.login(token);
                //将用户存入session域中
                ActiverUser activerUser = (ActiverUser) subject.getPrincipal();
                WebUtils.getSession().setAttribute("user",activerUser.getUser());

                //存入到日志中
                LogInfo LogInfo = new LogInfo();
                LogInfo.setLoginname(activerUser.getUser().getName()+"-"+activerUser.getUser().getLoginname());
                LogInfo.setLoginip(WebUtils.getRequest().getRemoteAddr());
                LogInfo.setLogintime(new Date());
                //保存
                this.ILogInfoService.save(LogInfo);
                return ResultObj.LOGIN_SUCCESS;
            }else {
                return ResultObj.LOGIN_ERROR_CODE;
            }
        }catch (AuthenticationException e){
            return ResultObj.LOGIN_ERROR_PASS;
        }
    }
}
